import { defineStore } from 'pinia'
import { ref } from 'vue'

interface UserInfo {
  userName?: string
  userId?: string
  avatar?: string
  accessToken?: string
  refreshToken?: string
  isVip?: boolean
  theme?: 'light' | 'dark'
  locale?: string
  followSystem?: boolean
  userBtnPerms?: string[]
  userPerms?: string[]
}

// 初始用户数据，可用户初始化
const initState = {
  userName: 'uni-plus',
  userId: '',
  avatar: '',
  accessToken: '',
  refreshToken: '',
  theme: <'light' | 'dark'> 'light',
  followSystem: false,
  locale: 'zh-CN',
  isVip: true,
  userBtnPerms: ['operation:user:create', 'operation:user:update'],
  userPerms: [],
}

export const useUserStore = defineStore(
  'user',
  // Setup Store 写法，Vue3 推荐用这个种方法写
  () => {
    const userInfo = ref<UserInfo>({ ...initState })

    // 设置用户信息 可设置部分信息（比如更新 token）
    const setUserInfo = (val: UserInfo): void => {
      userInfo.value = { ...userInfo.value, ...val }
      if (!!userInfo.value.accessToken && !!userInfo.value.refreshToken) {
        userInfo.value.userPerms.push('logined')
      }
      if (userInfo.value.isVip) {
        userInfo.value.userPerms.push('vip')
      }
    }

    // 清除用户信息
    const clearUserInfo = (): void => {
      userInfo.value = { ...initState }
    }

    // 获取页面权限信息
    const userPerms = computed(() => {
      return userInfo.value.userPerms || []
    })

    // 设置用户的权限
    const setUserPerms = (perms: string[]) => {
      userInfo.value.userPerms = perms
    }

    // 获取用户按钮权限
    const userBtnPerms = computed(() => {
      return userInfo.value.userBtnPerms || []
    })

    // 设置用户的按钮权限
    const setUserBtnPerms = (perms: string[]) => {
      userInfo.value.userBtnPerms = perms
    }

    // 获取主题状态
    const getTheme = computed(() => {
      return userInfo.value.theme
    })

    // 获取 locale
    const getLocale = computed(() => {
      return userInfo.value.locale
    })

    // 设置 locale
    const setLocale = () => {
      userInfo.value.locale = userInfo.value.locale === 'zh-CN' ? 'en-US' : 'zh-CN'
    }

    return {
      userInfo,
      getLocale,
      getTheme,
      userPerms,
      setUserPerms,
      userBtnPerms,
      setUserBtnPerms,
      setUserInfo,
      clearUserInfo,
      setLocale,
    }
  },
  {
    persist: true, // 是否持久化
  },
)
